// api/chat_api/chat_list.go
package chat_api

import (
	"github.com/gin-gonic/gin"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/models/ctype"
	"muziai-server/service/common"
	"muziai-server/utils/jwts"
	"muziai-server/utils/res"
)

type ChatListRequest struct {
	models.Page
	SessionID uint `json:"sessionID" form:"sessionID" binding:"required"`
}

type ChatListResponse struct {
	models.ChatModel
	SessionTitle string   `json:"sessionTitle"`
	RoleTitle    string   `json:"roleTitle"`
	RoleAvatar   string   `json:"roleAvatar"`
	UserNickname string   `json:"userNickname"`
	UserAvatar   string   `json:"userAvatar"`
	ImageList    []string `json:"imageList"`
}

func (ChatApi) ChatListView(c *gin.Context) {

	var cr ChatListRequest
	err := c.ShouldBindQuery(&cr)
	if err != nil {
		res.FailWithError(c, err)
		return
	}
	_claims, _ := c.Get("claims")
	claims := _claims.(*jwts.Claims)

	query := global.DB.Where("")
	if claims.Role == ctype.AuthRole {
		query.Where("user_id = ?", claims.UserID)
	}

	_list, count, _ := common.QueryList(models.ChatModel{
		SessionID: cr.SessionID,
	}, common.Option{
		Page:     cr.Page,
		Likes:    []string{"user_content"},
		Preloads: []string{"SessionModel", "RoleModel", "UserModel", "ImageList"},
		Where:    query,
		Sort:     "created_at desc",
	})

	var list = make([]ChatListResponse, 0)
	for _, model := range _list {
		var imageList = make([]string, 0)
		for _, imageModel := range model.ImageList {
			imageList = append(imageList, imageModel.ImageUrl)
		}
		list = append(list, ChatListResponse{

			ChatModel:    model,
			SessionTitle: model.SessionModel.Title,
			RoleTitle:    model.RoleModel.Title,
			RoleAvatar:   model.RoleModel.Avatar,
			UserNickname: model.UserModel.Nickname,
			UserAvatar:   model.UserModel.Avatar,
			ImageList:    imageList,
		})
	}

	res.OkWithList(c, list, count)
}
